package com.vimi8.chick.plugins.widgets.dialogs

import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.*
import cn.qqtheme.framework.picker.DatePicker
import cn.qqtheme.framework.picker.DateTimePicker
import com.vimi8.chick.plugins.R
import com.vimi8.chick.plugins.utils.DateTimeUtil
import kotlinx.android.synthetic.main.common_dialog_date_range_select.*
import java.util.*

class DateRangeSelectDialog : BaseDialogFragment() {

    companion object {
        fun newInstance() = DateRangeSelectDialog()
        const val START_DELTA = "start_delta"
        const val END_DELTA = "end_delta"
        const val START_TIME = "start_time"
        const val END_TIME = "end_time"
    }

    private var mOnDateRangeSelectListener: OnDateRangeSelectListener? = null

    private lateinit var datePickStart: DatePicker
    private lateinit var datePickEnd: DatePicker

    private var hideOnSelect = true
    private var shortcutVisible = false

    private var startDelta = 7
    private var endDelta = 0
    private var startTime: String? = ""
    private var endTime: String? = ""

    override fun getResourceId(): Int = R.layout.common_dialog_date_range_select

    override fun initData(savedInstanceState: Bundle?) {
        val bundle = arguments
        if (bundle != null) {
            startDelta = bundle.getInt(START_DELTA)
            endDelta = bundle.getInt(END_DELTA)
            startTime = bundle.getString(START_TIME)
            endTime = bundle.getString(END_TIME)
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        dialog.setCanceledOnTouchOutside(true)
        initDatePicker()
        bindEvent()
    }

    private fun initDatePicker() {
        if (startTime.isNullOrEmpty() || endTime.isNullOrEmpty()) {
            setDatePicker(startDelta, endDelta)
        } else {
            val startDate = DateTimeUtil.parseDate(startTime!!, DateTimeUtil.DF_YYYY_MM_DD)
            val endDate = DateTimeUtil.parseDate(endTime!!, DateTimeUtil.DF_YYYY_MM_DD)
            if (startDate == null || endDate == null) {
                setDatePicker(startDelta, endDelta)
            } else {
                setDatePicker(
                    DateTimeUtil.getYear(startDate),
                    DateTimeUtil.getMonth(startDate),
                    DateTimeUtil.getDay(startDate),
                    DateTimeUtil.getYear(endDate),
                    DateTimeUtil.getMonth(endDate),
                    DateTimeUtil.getDay(endDate),
                    15, 15
                )
            }
        }
    }

    private fun bindEvent() {
        mDateSelectWeekBtn.setOnClickListener { onTimeSelectDelta(7) }
        mDateSelectMonthBtn.setOnClickListener { onTimeSelectDelta(30) }
        mDateSelectQuarterBtn.setOnClickListener { onTimeSelectDelta(90) }
        mDateSelectDismissBtn.setOnClickListener {
            this.mOnDateRangeSelectListener?.onDismiss()
            onSelectDismiss()
        }
        mDateSelectResetBtn.setOnClickListener {
            this.mOnDateRangeSelectListener?.onReset()
            onSelectDismiss()
        }
        mDateSelectSubmitBtn.setOnClickListener { onTimeSelectSubmit() }
    }

    private fun setWheelView() {
        mShortcutBtnLl.visibility = if (shortcutVisible) View.VISIBLE else View.GONE
        mDateSelectStartFl.removeAllViews()
        mDateSelectEndFl.removeAllViews()
        mDateSelectStartFl.addView(datePickStart.contentView)
        mDateSelectEndFl.addView(datePickEnd.contentView)
    }

    private fun onTimeSelectDelta(delta: Int) {
        val calendar = Calendar.getInstance()
        val yearEnd = calendar.get(Calendar.YEAR)
        val monthEnd = calendar.get(Calendar.MONTH) + 1
        val dayEnd = calendar.get(Calendar.DAY_OF_MONTH)
        datePickEnd.setSelectedItem(yearEnd, monthEnd, dayEnd)

        calendar.add(Calendar.DATE, -1 * delta)
        val yearStart = calendar.get(Calendar.YEAR)
        val monthStart = calendar.get(Calendar.MONTH) + 1
        val dayStart = calendar.get(Calendar.DAY_OF_MONTH)
        datePickStart.setSelectedItem(yearStart, monthStart, dayStart)

        setWheelView()

        this.mOnDateRangeSelectListener?.onSelect(yearStart, monthStart, dayStart, yearEnd, monthEnd, dayEnd)

        onSelectDismiss()
    }

    private fun onTimeSelectSubmit() {
        val yearStart = datePickStart.selectedYear.toInt()
        val monthStart = datePickStart.selectedMonth.toInt()
        val dayStart = datePickStart.selectedDay.toInt()

        val yearEnd = datePickEnd.selectedYear.toInt()
        val monthEnd = datePickEnd.selectedMonth.toInt()
        val dayEnd = datePickEnd.selectedDay.toInt()

        this.mOnDateRangeSelectListener?.onSelect(yearStart, monthStart, dayStart, yearEnd, monthEnd, dayEnd)

        onSelectDismiss()
    }

    fun setHideOnSelect(hide: Boolean) {
        this.hideOnSelect = hide
    }

    fun setShortcutButtonVisible(visible: Boolean) {
        this.shortcutVisible = visible
    }

    private fun setDatePicker(startDelta: Int, endDelta: Int) {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        setDatePicker(year, month, day, year, month, day, startDelta, endDelta)
    }

    private fun setDatePicker(ys: Int, ms: Int, ds: Int, ye: Int, me: Int, de: Int, startDelta: Int, endDelta: Int) {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val startYear = year - startDelta
        val endYear = year + endDelta
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        datePickEnd = DatePicker(activity, DateTimePicker.YEAR_MONTH_DAY)
        datePickEnd.setRangeStart(startYear, month, day)
        datePickEnd.setRangeEnd(endYear, month, day)
        datePickEnd.setSelectedItem(ye, me, de)
        datePickEnd.setOffset(2)
        datePickEnd.setTextColor(ContextCompat.getColor(context!!, R.color.common_color_primary))
        datePickEnd.setLineSpaceMultiplier(2f)

        datePickStart = DatePicker(activity, DateTimePicker.YEAR_MONTH_DAY)
        datePickStart.setRangeStart(startYear, month, day)
        datePickStart.setRangeEnd(endYear, month, day)
        datePickStart.setSelectedItem(ys, ms, ds)
        datePickStart.setOffset(2)
        datePickStart.setTextColor(ContextCompat.getColor(context!!, R.color.common_color_primary))
        datePickStart.setLineSpaceMultiplier(2f)

        setWheelView()
    }

    private fun onSelectDismiss() {
        if (hideOnSelect) dialog.dismiss()
    }

    override fun onResume() {
        super.onResume()
        val dialogWindow = dialog.window
        dialogWindow.setGravity(Gravity.BOTTOM)
        dialogWindow.decorView.setPadding(0, 0, 0, 0)

        val lp = dialogWindow!!.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialogWindow.attributes = lp
    }

    interface OnDateRangeSelectListener {
        fun onSelect(ys: Int, ms: Int, ds: Int, ye: Int, me: Int, de: Int)
        fun onDismiss()
        fun onReset()
    }

    fun setOnDateRangeSelectListener(listener: OnDateRangeSelectListener) {
        this.mOnDateRangeSelectListener = listener
    }
}
